package com.bw.dao;

import com.bw.pojo.Goods;
import com.bw.util.JDBC;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/***************************
 FileAction:

 CreateTime:2022-04-08 9:28
 Author:Aaking-aline
 ****************************/
public class GoodsDao {



    public List<Goods> selectAllGoods() throws SQLException {
        String sql = "select * from goods";
        Connection connection = JDBC.getConnection();
        PreparedStatement ps = connection.prepareStatement(sql);

        ResultSet rs = ps.executeQuery();

        List<Goods> list = new ArrayList<>();

        while (rs.next()){
            Goods goods = new Goods(rs.getInt(1),
                    rs.getString(2),
                    rs.getString(3),
                    rs.getDouble(4),
                    rs.getInt(5),
                    rs.getString(6),
                    rs.getString(7),
                    rs.getString(8));
            list.add(goods);
        }

        return list;
    }

    public int insertGoods(Goods goods) throws SQLException {
        String sql = "insert into goods values(null,?,?,?,?,?,?,?)";
        Connection connection = JDBC.getConnection();
        PreparedStatement ps = connection.prepareStatement(sql);

        ps.setObject(1,goods.getGoods_name());
        ps.setObject(2,goods.getGoods_kind());
        ps.setObject(3,goods.getGoods_price());
        ps.setObject(4,goods.getGoods_stock());
        ps.setObject(5,goods.getGoods_makeaddr());
        ps.setObject(6,goods.getGoods_makedate());
        ps.setObject(7,goods.getGoods_quality());

        int i = ps.executeUpdate();

        JDBC.close(ps,connection);

        return i;
    }

    public int deleteGoodsById(String id) throws SQLException {
        // 不管单删 还是多选删除  只要改这个sql语句  就都可以通过这个方法来实现
        String sql = "delete from goods where id in(" + id + ")";  // id = 3,5,6,7
        Connection connection = JDBC.getConnection();
        PreparedStatement ps = connection.prepareStatement(sql);

        int i = ps.executeUpdate();
        JDBC.close(ps,connection);
        return i;
    }
}
